package controller

import (
	"fmt"
	"gin/CloudRestaurant/model"
	"gin/CloudRestaurant/service"
	"gin/CloudRestaurant/tool"
	"github.com/gin-gonic/gin"
	"strconv"
)

type StudentController struct {

}

func (sc *StudentController)Router(engine *gin.RouterGroup)  {
	// 插入一条 学生数据
	engine.POST("/api/insetStudent",sc.InsertStuCon )
	// 根据学号查询一条数据
	engine.GET("/api/findByStu/:number",tool.CacheDecorator(sc.FindByStu,"number","0_number_%s",model.Student{}))
	// 测试上下文
	engine.GET("/api/testAPi",sc.testApi)
}



// 测试上下文机制
func (sc *StudentController) testApi(context *gin.Context)  {

}


// 插入一条学生数据
func (sc *StudentController) InsertStuCon(context *gin.Context)  {
	var student model.Student
	err:= context.ShouldBind(&student)
	if err!=nil{
		tool.Failed(context,"失败")
		return
	}
	tool.Success(context,student)
	return
}

// 根据 学号查询学生
func (sc *StudentController)FindByStu(context *gin.Context)  {
	number := context.Param("number") // 获得输入的学号
	int64, err := strconv.ParseInt(number, 10, 64)
	if err != nil{
		tool.Failed(context,"解析参数失败")
		return
	}
	// 传入值到context中
	context.Set("value",number)
	stuSer := service.StudentService{}
	stu := stuSer.FinOneByNgmber(int64)
	if stu == nil{
		tool.Failed(context,"查询失败 记录可能不存在")
	}
	tool.Success(context,&stu)
	fmt.Println("查询成功")
}
